<template>
  <div class="fund-password-page">
    <ResponsiveNav />

    <div class="page-content">
      <!-- 面包屑导航 -->
      <div class="page-nav">
        <div class="breadcrumb">
          <el-breadcrumb separator="/">
            <el-breadcrumb-item :to="{ path: '/account/security' }">
              <i class="fas fa-chevron-left"></i> {{ $t('返回登录与安全') }}
            </el-breadcrumb-item>
            <el-breadcrumb-item>{{ hasFundPassword ? $t('修改资金密码') : $t('设置资金密码') }}</el-breadcrumb-item>
          </el-breadcrumb>
        </div>
      </div>

      <!-- 主要内容 -->
      <div class="main-card">
        <h1 class="page-title">{{ hasFundPassword ? $t('修改资金密码') : $t('设置资金密码') }}</h1>

        <el-form ref="formRef" :model="form" :rules="rules" label-position="top" class="password-form">
          <!-- 登录密码 (仅修改时显示) -->

          <el-form-item :label="$t('邮箱地址')" prop="username">
            <el-input v-model="form.username" type="email" :placeholder="$t('请输入邮箱地址')">
              <!-- <template #prefix>
                <i class="fas fa-key"></i>
              </template> -->
            </el-input>
          </el-form-item>
          <el-form-item :label="$t('验证码')" prop="verifyCode">
            <el-input v-model="form.verifyCode" type="text" :placeholder="$t('请输入验证码')">
              <!-- <template #prefix>
                <i class="fas fa-key"></i>
              </template> -->
            </el-input>
            <div>
              <el-button link :disabled="countdown > 0" @click="handleResend" style="color: #f0c14b;">
                {{ countdown > 0 ? `${$t('重新发送')} (${countdown}s)` : $t('发送验证码') }}
              </el-button>
            </div>
          </el-form-item>
          <!-- <el-form-item :label="$t('登录密码')" prop="LogoPassword">
            <el-input v-model="form.LogoPassword" type="password" :placeholder="$t('请输入登录密码')" show-password>
            </el-input>
          </el-form-item> -->
          <!-- 当前资金密码 (仅修改时显示) -->
          <el-form-item v-if="!hasFundPassword" :label="$t('当前资金密码')" prop="currentPassword">
            <el-input v-model="form.currentPassword" type="password" :placeholder="$t('请输入当前资金密码')" show-password>
              <!-- <template #prefix>
                <i class="fas fa-lock"></i>
              </template> -->
            </el-input>
          </el-form-item>

          <el-form-item :label="$t('新资金密码')" prop="newPassword">
            <el-input v-model="form.newPassword" type="password" :placeholder="$t('请输入新资金密码')" show-password>
              <!-- <template #prefix>
                <i class="fas fa-key"></i>
              </template> -->
            </el-input>
            <div class="password-requirements">
              <p>{{ $t('密码要求') }}：</p>
              <ul>
                <li :class="{ valid: hasLength }">{{ $t('6位纯数字') }}</li>
                <li :class="{ valid: !hasLetter }">{{ $t('不能包含字母') }}</li>
                <li :class="{ valid: !hasSpecial }">{{ $t('不能包含特殊字符') }}</li>
                <li :class="{ valid: !hasSequential }">{{ $t('不能使用连续数字') }}</li>
                <li :class="{ valid: !hasSame }">{{ $t('不能使用相同数字') }}</li>
              </ul>
            </div>
          </el-form-item>

          <el-form-item :label="$t('确认新密码')" prop="confirmPassword">
            <el-input v-model="form.confirmPassword" type="password" :placeholder="$t('请再次输入新资金密码')" show-password>
              <!-- <template #prefix>
                <i class="fas fa-key"></i>
              </template> -->
            </el-input>
          </el-form-item>

          <!-- <div class="a-form-field"   >
                <label class="a-form-label">{{ $t('验证码') }}</label>
                <div>
                  <div>
                  <input
                  v-model="form.emailCode"
                  class="a-input-text"
                  :class="{ 'a-form-error': formError }"
                  :placeholder="$t('请输入验证码')"
                  @blur="validateEmailCod"
                />
                </div>
                <div>
                  <el-button link :disabled="countdown > 0" @click="handleResend" style="color: #f0c14b;">
                      {{ countdown > 0 ? `${$t('重新发送')} (${countdown}s)` : $t('发送验证码') }}
                    </el-button>
                </div>
                </div>
                <div v-if="formError && errorMessage" class="a-alert-error">
                  {{ errorMessage }}
                </div>
              </div> -->
          <!-- 手机验证码 -->
          <!-- <el-form-item label="手机验证码" prop="verifyCode">
            <div class="verify-code-input">
              <div>
                  <input
                  v-model="form.verifyCode"
                  class="a-input-text"
                  :placeholder="$t('请输入验证码')"
              
                />
                </div>
                <div>
                  <el-button link :disabled="countdown > 0" @click="handleResend" style="color: #f0c14b;">
                      {{ countdown > 0 ? `${$t('重新发送')} (${countdown}s)` : $t('发送验证码') }}
                    </el-button>
                </div>
            </div>
          </el-form-item> -->

          <!-- 底部按钮 -->
          <div class="form-actions">
            <el-button @click="handleCancel">{{ $t('取消') }}</el-button>
            <el-button type="primary" :loading="loading" @click="handleSubmit">
              {{ $t('确认') }}{{ hasFundPassword ? $t('修改') : $t('设置') }}
            </el-button>
          </div>
        </el-form>
      </div>
    </div>

    <Footer />
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import Footer from '@/components/Footer.vue'
import { ApiSendEmail } from '@/api/public'

import VerificationCodeInput from '../profile/components/VerificationCodeInput.vue'
import { walletUpdateP,setwalletUpdateP } from '@/api/mine'
import { useI18n } from "vue-i18n";
const { t } = useI18n();
const router = useRouter()
const formRef = ref<FormInstance>()
const loading = ref(false)
const verifyError = ref(false)
const countdown = ref(0)
const twoFactorEnabled = ref(false) // 从状态管理或API获取
import useUserStore from '@/store/modules/user'

const userStore = useUserStore()

// 模拟数据 - 是否已设置资金密码
// const hasFundPassword = ref(false)
const hasFundPassword = ref(userStore.userInfo?.wallet?.walletPassword);

// console.log(userStore.userInfo?.wallet?.walletPassword,'userInfo');

const form = ref({
  currentPassword: '',
  newPassword: '',
  confirmPassword: '',
  verifyCode: '',
  LogoPassword: '',
  username: userStore.userInfo?.member?.email
})

// 密码强度校验
const hasLength = computed(() => form.value.newPassword.length === 6)
const hasLetter = computed(() => /[a-zA-Z]/.test(form.value.newPassword))
const hasSpecial = computed(() => /[^0-9]/.test(form.value.newPassword))
const hasSequential = computed(() => {
  const pwd = form.value.newPassword
  return /012|123|234|345|456|567|678|789/.test(pwd) ||
    /987|876|765|654|543|432|321|210/.test(pwd)
})
const hasSame = computed(() => {
  const pwd = form.value.newPassword
  return /(\d)\1{2,}/.test(pwd)
})

const validatePass = (rule: any, value: string, callback: any) => {
  if (value === '') {
    callback(new Error(t('请输入资金密码')))
  } else if (value.length !== 6) {
    callback(new Error(t('资金密码必须为6位')))
  } else if (!/^\d+$/.test(value)) {
    callback(new Error(t('资金密码只能包含数字')))
  } else if (hasSequential.value) {
    callback(new Error(t('资金密码不能使用连续数字')))
  } else if (hasSame.value) {
    callback(new Error(t('资金密码不能使用相同数字')))
  } else {
    callback()
  }
}

const validateConfirmPass = (rule: any, value: string, callback: any) => {
  if (value === '') {
    callback(new Error(t('请再次输入资金密码')))
  } else if (value !== form.value.newPassword) {
    callback(new Error(t('两次输入密码不一致')))
  } else {
    callback()
  }
}

const rules: FormRules = {
  username: [
    { required: true, message: t('请填写邮箱地址'), trigger: 'blur' }
  ],
  currentPassword: [
    { required: true, message: t('请输入当前资金密码'), trigger: 'blur' }
  ],
  LogoPassword: [
    { required: true, message: t('请输入当登录密码'), trigger: 'blur' }
  ],
  newPassword: [
    { required: true, validator: validatePass, trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, validator: validateConfirmPass, trigger: 'blur' }
  ],

  verifyCode: [
    { required: true, message: '请输入验证码', trigger: 'blur' },
    // { len: 6, message: '请输入6位验证码', trigger: 'blur' }
  ]
}

const startCountdown = (type) => {
  ApiSendEmail({ email: form.value.username }).then(res => {
    ElMessage.success(res.msg || t('验证码已发送'))
    const target = countdown
    target.value = 60
    const timer = setInterval(() => {
      target.value--
      if (target.value <= 0) clearInterval(timer)
    }, 1000)
  }).catch(() => {
    ElMessage.error(t('发送失败'))
  })
  // countdown.value = 60
  // const timer = setInterval(() => {
  //   countdown.value--
  //   if (countdown.value <= 0) {
  //     clearInterval(timer)
  //   }
  // }, 1000)
}

const handleResend = async () => {
  try {

    if (form.value.username == '') {
      return ElMessage.error(t('请填写邮箱地址'))
    }
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
    if (!emailRegex.test(form.value.username)) {
      return ElMessage.error(t('请输入有效的邮箱地址'))
    }
    // TODO: 调用发送验证码API
    await new Promise(resolve => setTimeout(resolve, 500))
    startCountdown('current')

  } catch (error) {
    ElMessage.error(t('发送失败，请重试'))
  }
}

const handleVerifyComplete = () => {
  verifyError.value = false
}

const handleSubmit = async () => {
  if (!formRef.value) return

  try {
    await formRef.value.validate()
    loading.value = true
    let obj = {
      emailCode:form.value.verifyCode,
      // loginPassword: form.value.LogoPassword,
      password: form.value.newPassword
    }
    //修改资金密码
    let res = await walletUpdateP(obj)
    //设置资金密码
    // let res = await setwalletUpdateP(obj)
    
    // TODO: 调用设置/修改资金密码API
    // await new Promise(resolve => setTimeout(resolve, 1000))

    if (res.code == 200) {
      ElMessage.success(`${t('资金密码')}${hasFundPassword.value ? t('修改') : t('设置')}${t('成功')}`)
      router.push('/account/security')
    }
  } catch (error) {
    console.error('验证失败:', error)
  } finally {
    loading.value = false
  }
}

const handleCancel = () => {
  router.push('/account/security')
}

// 检查是否已绑定谷歌验证器
onMounted(async () => {
  userStore.getInfo();
  // TODO: 从API获取谷歌验证器状态
  // if (!twoFactorEnabled.value) {
  //   ElMessage.warning('请先绑定谷歌验证器')
  //   router.push('/account/security/2fa')
  // }
})

// // 初始发送验证码
// startCountdown();

</script>

<style lang="scss" scoped>
.fund-password-page {
  background-color: #f8f8f8;
  min-height: 100vh;
  display: flex;
  flex-direction: column;
}

.page-content {
  padding: 32px 24px;
  max-width: 800px;
  margin: 0 auto;
  width: 100%;
  flex: 1;
}

.page-nav {
  margin-bottom: 24px;

  .breadcrumb {
    :deep(.el-breadcrumb__item) {
      .el-breadcrumb__inner {
        color: #565656;
        font-weight: normal;
        font-size: 14px;

        &:hover {
          color: #c45500;
        }

        i {
          margin-right: 4px;
          font-size: 12px;
        }
      }
    }
  }
}

.main-card {
  background: white;
  border-radius: 8px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);
  padding: 32px;
}

.page-title {
  font-size: 24px;
  color: #111;
  font-weight: 500;
  margin-bottom: 32px;
}

.password-form {
  max-width: 400px;
  margin: 0 auto;

  :deep(.el-form-item__label) {
    color: #333;
    font-weight: 500;
    padding-bottom: 8px;
  }

  :deep(.el-input__wrapper) {
    padding-left: 0;
  }

  :deep(.el-input__prefix) {
    width: 40px;
    justify-content: center;
    color: #999;
  }

  :deep(.el-input__inner) {
    padding-left: 40px;
  }
}

.password-requirements {
  margin-top: 16px;
  color: #666;
  font-size: 14px;

  p {
    margin-bottom: 8px;
  }

  ul {
    list-style: none;
    padding: 0;
    margin: 0;

    li {
      display: flex;
      align-items: center;
      margin-bottom: 4px;
      color: #ff4d4f;

      &::before {
        content: '\f00d';
        font-family: 'Font Awesome 5 Free';
        font-weight: 900;
        margin-right: 8px;
        font-size: 12px;
      }

      &.valid {
        color: #52c41a;

        &::before {
          content: '\f00c';
        }
      }
    }
  }
}

.verify-code-input {
  .resend-wrapper {
    margin-top: 16px;
    text-align: center;
  }
}

.form-actions {
  margin-top: 40px;
  display: flex;
  justify-content: flex-end;
  gap: 16px;

  .el-button {
    min-width: 100px;
  }
}

@media (max-width: 768px) {
  .page-content {
    padding: 16px;
  }

  .main-card {
    padding: 24px 16px;
  }

  .page-title {
    font-size: 20px;
    margin-bottom: 24px;
  }
}
</style>
